#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <signal.h>
#include "Log.hpp"
#include "ThreadPool.hpp"
#include "Task.hpp"
#include "Daemon.hpp"

extern Log lg;

enum
{
    UsageError = 1,
    SocketError,
    BindError,
    ListenError,
};

const int defaultnum = 12;
const uint16_t defaultport = 8889;
const std::string defaultip = "0.0.0.0";
const int backlog = 10; // 一般不要设置太大

class Server;

// class ThreadData
// {
// public:
//     ThreadData(int fd, const std::string &ip, const uint16_t &p, Server *t) : sockfd(fd), clientip(ip), clientport(p), tsvr(t)
//     {
//     }

// public:
//     int sockfd;
//     std::string clientip;
//     uint16_t clientport;
//     Server *tsvr;
// };

class Server
{
public:
    Server(const uint16_t &port = defaultport, int listensock = defaultnum, const std::string &ip = defaultip)
        : _listensock(listensock), _port(port), _ip(ip)
    {
    }

    void ServerInit()
    {
        // 创建套接字
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg(Fatal, "create listensock, errno: %d, errstring: %s", errno, strerror(errno));
            exit(SocketError);
        }
        lg(Info, "create listensock success, listensock: %d", _listensock);

        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)); // 防止偶发性的服务器无法立即重启

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        inet_aton(_ip.c_str(), &(local.sin_addr));
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());

        socklen_t len = sizeof(local);

        // 绑定套接字
        if (bind(_listensock, (const sockaddr *)&local, len) < 0)
        {
            lg(Fatal, "bind listensock, errno: %d, errstring: %s", errno, strerror(errno));
        }
        lg(Info, "bind listensocket success, listensocket: %d", _listensock);

        // Tcp是面向连接的，服务器一般是比较“被动的”，服务器一直处于一种，一直在等待连接到来的状态
        // 设置监听状态
        if (listen(_listensock, backlog) < 0)
        {
            lg(Fatal, "listen listensock, errno: %d, errstring: %s", errno, strerror(errno));
        }
        lg(Info, "listen listensocket success, listensocket: %d", _listensock);
    }

    // static void *Routine(void *args)
    // {
    //     pthread_detach(pthread_self());
    //     ThreadData *td = static_cast<ThreadData *>(args);
    //     td->tsvr->Service(td->sockfd, td->clientip, td->clientport);
    //     delete td;
    //     return nullptr;
    // }

    void ServerStart()
    {
        // signal(SIGCHLD, SIG_IGN);
        // signal(SIGPIPE, SIG_IGN);
        Daemon();

        lg(Info, "tcpServer is running...");

        while (true)
        {
            // 获取新连接
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = accept(_listensock, (sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                lg(Fatal, "accept error, errno: %d, errstring: %s", errno, strerror(errno));
                continue;
            }

            lg(Info, "accept success, listensocket: %d", _listensock);

            uint16_t clientport = ntohs(client.sin_port);
            char clientip[32];
            inet_ntop(AF_INET, &(client.sin_addr), clientip, sizeof(clientip));

            // 2. 根据新连接来进行通信
            lg(Info, "get a new link..., sockfd: %d, client ip: %s, client port: %d", sockfd, clientip, clientport);

            // version 1 -- 单进程版
            // Service(sockfd, clientip, clientport);
            // close(sockfd);

            // version 2 -- 多进程版
            // pid_t id = fork();
            // if(id == 0)
            // {
            //     // child
            //     close(_listensock);
            //     if(fork() > 0) exit(0);
            //     Service(sockfd, clientip, clientport); //孙子进程， system 领养
            //     close(sockfd);
            //     exit(0);
            // }
            // close(sockfd);
            // // father
            // pid_t rid = waitpid(id, nullptr, 0);
            // (void)rid;

            // version 3 -- 多线程版本
            // ThreadData *td = new ThreadData(sockfd, clientip, clientport, this);
            // pthread_t tid;
            // pthread_create(&tid, nullptr, Routine, td);

            // version 4 --- 线程池版本
            ThreadPool<Task>::GetInstance()->start();
            Task t(sockfd, clientip, clientport);
            ThreadPool<Task>::GetInstance()->push(t);
        }
    }

    void Service(int sockfd, const std::string &ip, const uint16_t &port)
    {
        char buffer[4096];

        while (true)
        {
            ssize_t n = read(sockfd, buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << buffer << std::endl;

                std::cout << "client say# " << buffer << std::endl;
                std::string echo_string = "tcpserver echo# ";
                echo_string += buffer;

                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                lg(Info, "%s:%d quit, server close sockfd: %d", ip.c_str(), port, sockfd);
                break;
            }
            else
            {
                lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", sockfd, ip.c_str(), port);
                break;
            }
        }
    }

private:
    int _listensock;
    uint16_t _port;
    std::string _ip;
};